$(function(){
	$(document).keydown(function (event) {  
	    if (event.keyCode == 116) {  
	    	var ids ="";
	    	$(".add_comment .inner").each(function(i,element){
	    		var commentId = $(this).find("input[name=commentId]").val() ;
	    		if(CommnUtil.notNull(commentId)){			
	    			ids += commentId + ",";		
	    		}	
	    	});
	    	if(CommnUtil.notNull(ids)){
/*
	            layer.confirm("上传的图片将被删除,确定刷新吗？",{skin: 'layui-layer-red ',offset: ['40%', '40%']},function(index){

	            	  //将用户没有完成的评论信息(如图片信息)
	    		    deleteCommentsByIds(ids);
	        	});*/
	    		 if (confirm("上传的图片将被删除,确定刷新吗？")) {
		    		    //将用户没有完成的评论信息(如图片信息)
		    		    deleteCommentsByIds(ids);
		                return true;   
		            } else  {
		                return false; 
		            } 
	    	}                  
	    }  
   });  
	$(document).on("click",".add_comment  .show_pic > span > span",function(){
		var commentId = $(this).parents(".inner").find("input[name='commentId']").val();
		var filePicture = $(this).prev().attr("filed");
		deleteConsultCommentPic(commentId,filePicture);
		$(this).parent().remove();
	});
	$(document).on("mouseover",".add_comment  .show_pic > span",function(){
		$(this).find('span').css('display','block');
	});
	$(document).on("mouseout",".add_comment  .show_pic > span",function(){

		$(this).find('span').css('display','none');
	});

	$(document).on("change",".add_comment .inner .right .sun_photo > input",function(){
	    var $file = $(this);
		var fileObj = $file[0];
		var windowURL = window.URL || window.webkitURL;
		var dataURL;
		var $p =$(this).parent().siblings(".show_pic");
		var $imgLength = $(this).parent().siblings(".show_pic").children().length;
		var $num =3-$imgLength;
		if(fileObj && fileObj.files){
			if(fileObj.files.length > 3 || $imgLength >= 3  || fileObj.files.length+ $imgLength > 3){
			    layer.msg("最多只能选择三个图片,你还能上传"+ $num +"个图片" ,{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:2000});
			    return false;
			}					
			for(var i =0; i< fileObj.files.length; i++){
				var  field ="";
				if(i== 0)
					field = "filePicture";
				if(i == 1)
					field = "filePicture2";
				if(i == 2)
					field = "filePicture3";
				if( fileObj.files[i]){
					dataURL = windowURL.createObjectURL(fileObj.files[i]);						
					var $img='<span>'
								+'<img src="' + dataURL + '" alt="评论图片" filed ="'+field+'" />'
								+'<span style=""><img src="'+rootPath+'/images/add_del.png" alt="" /></span>'
					        +'</span>';
					$p.append($img);
					//$($img).append('<span><img src="'+rootPath+'/images/add_del.png" alt="" /></span>');
				 
				}else{
					dataURL = $file.val();
					var imgObj = $(this).parent().siblings(".show_pic > span > img");
					// 两个坑:
					// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
					// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
				//	imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
				//		imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
				
					
					var $img='<span>'
						+'<img src="' + dataURL + '" alt="评论图片" filed ="'+field+'"  />'
						+'<span style=""><img src="'+rootPath+'/images/add_del.png" alt="" /></span>'
			        +'</span>';
		          	$p.append($img);
					 
				}
			}
		}
		var goodsId = $(this).parent().parent().parent().parent().find("input[name=goodsId]").val();
	  //	alert(goodsId);
		//开始上传图片
		ajaxUploadFiles(goodsId,$(this).attr("id"),$(this).parent().parent().parent().parent().find("input[name=goodsId]"));
		
	});
	
	$(".add_comment button").click(function(){
		var flag= true;
		$(".add_comment .inner .right textarea").each(function(){
			if(CommnUtil.notNull($(this).val()) == false){
			    layer.msg("订单评论不能为空",{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:2000});
				flag = false;
				return false;
			}
		});
		if(flag){
			//提交评论
			comment();
		}else{
			return false;
		}
		
	});

});

//删除用户离开没有完成提交的评论图片
function deleteCommentsByIds(ids){
	var url = rootPath + "/consultComment/deleteCommentsByIds";
	var result = CommnUtil.ajax(url,{ids:ids},"json");
	if(result.resultSuccess == true){
		   window.location.reload();
	}else if(result.resultSuccess == false){
		console.log(result.resultDesc);
	}
}
//提交订单商品评论
function comment(){
	var url =rootPath + "/consultComment/updateConsultComments";
	var data={};
	var comments =[];
	//var filePathIds=[];
	$(".add_comment .inner").each(function(i,element){
		//filePathIds.push('filePath'+ $(this).find("input[name=goodsId]").val());
		var comment ={};
		comment["goodsId"] = $(this).find("input[name=goodsId]").val();
		comment["id"]= $(this).find("input[name=commentId]").val();		
		comment["specInfo"] =$(this).find("input[name=specInfo]").val();
		comment["orderId"] =$(".add_comment").find("input[name = orderId]").val();
		comment["consultContent"] = $(this).find(".right textarea[name=consultContent]").val();
		comment["type"] ='2';  //类型：1、咨询内容 2、评价晒单 3、我的足迹
		comments.push(comment);
	});
	var param = encodeURI(JSON.stringify(comments));
	data["param"] = param;	
	var result = CommnUtil.ajax(url,data,"json");
	if(result.resultSuccess == true){
		  layer.msg("评论成功",{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon: 1,time:100000});
		    Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
		 		var $url = rootPath + '/order/orderPage?queryStatus=0';		
				location.href=$url;
		     }
	}else if(result.resultSuccess == false){
		layer.msg(result.resultDesc,{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:6000});	
	}
	
}

//上传评论图片，并生成评论记录
function ajaxUploadFiles(goodsId,filePathId,$goodsId){
	var orderId = $(".add_comment input[name=orderId]").val();
	var url =rootPath + "/consultComment/addConsultCommentPic";
	$.ajaxFileUpload({
		  url:url,//需要链接到服务器地址   
		  type:'post',
		  data:{'goodsId':goodsId,'orderId':orderId},
	      secureuri:false,  
	      fileElementId:filePathId,//文件选择框的id属性  
	      dataType: 'JSON',   //json 
	      success: function (result) {  
	    	  result =JSON.parse($(result).text());
	    	  if(result.resultSuccess == true){
	    		  var  commentId = result.commentId;
	    		  $goodsId.parent().find("input[name=commentId]").val(commentId);	    		  
	    		}else if(result.resultSuccess == false){
	    		    layer.msg(result.resultDesc,{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:2000});	
	    		}
	    	  
	      }, 
	      error : function(data, status, e){ 
	    	  layer.msg('图片上传失败！',{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:2000});
	  	   } 
	});
}
/**
 * 删除一个评论图片
 * @param commentId
 * @param filePicture
 */
function deleteConsultCommentPic(commentId,filePicture){
	var url = rootPath + "/consultComment/deleteConsultCommentPic";
	var data = {};
	data["commentId"] = commentId;
	data["filePicture"] = filePicture;
	var result = CommnUtil.ajax(url,data,"json");
	if(result.resultSuccess == true){
	    layer.msg("图片删除成功！",{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:1,time:2000});
	}else if(result.resultSuccess == false){
	    layer.msg(result.resultDesc,{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon:2,time:2000});
	}
}

